package com.wtzz.police.base.config;

import com.wtzz.police.base.entity.User;
import com.wtzz.police.base.model.enums.Role;
import com.wtzz.police.base.model.enums.RoleCheckType;
import com.wtzz.police.base.model.enums.WtzzResponse;
import com.wtzz.police.base.model.exception.WtzzRuntimeException;
import com.wtzz.police.base.model.annotaions.RoleCheck;
import com.wtzz.police.base.util.WebTool;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * 角色检查拦截器
 */
@Component
public class RoleCheckInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler instanceof HandlerMethod) {
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            RoleCheck roleCheck = method.getAnnotation(RoleCheck.class);
            if (roleCheck != null) {
                Role[] roles = roleCheck.value();//获取方法中设置的权限信息
                RoleCheckType type = roleCheck.type();
                if (roles.length != 0) {
                    User user = WebTool.getCurrentUser();
                    if (user == null) return true;
                    if (type == RoleCheckType.ONLY) {
                        if (!ArrayUtils.contains(roles, user.getRole())) {
                            throw new WtzzRuntimeException(WtzzResponse.ACCESS_DENIED, "该用户没有权限");
                        }
                    } else if (type == RoleCheckType.EXCLUDE) {
                        if (ArrayUtils.contains(roles, user.getRole())) {
                            throw new WtzzRuntimeException(WtzzResponse.ACCESS_DENIED, "该用户没有权限");
                        }
                    }
                }
            }
        }
        return true;
    }
}